package com.dreamweaver.mvvmtest.widget;

import android.content.Context;
import android.util.AttributeSet;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.LifecycleRegistry;
import androidx.lifecycle.Observer;

import com.dreamweaver.LiveDataStore;

public class LifecycleView extends AppCompatTextView implements LifecycleOwner {
    LifecycleRegistry lifecycleRegistry = new LifecycleRegistry(this);

    public LifecycleView(Context context) {
        super(context);
        init(context, null, 0);
    }

    public LifecycleView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs, 0);
    }

    public LifecycleView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs, defStyleAttr);
    }

    private void init(Context context, AttributeSet attrs, int defStyleAttr) {
        lifecycleRegistry.markState(Lifecycle.State.RESUMED);
        LiveDataStore.getIntegerMutableLiveData().observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(Integer integer) {
                setText("" + integer.intValue());
            }
        });
    }

    @NonNull
    @Override
    public Lifecycle getLifecycle() {
        return lifecycleRegistry;
    }

    public void disable() {
        lifecycleRegistry.markState(Lifecycle.State.CREATED);
    }
}
